package com.lagou.edu.service;

import com.lagou.edu.clinet.CodeService;
import com.lagou.edu.domain.User;
import com.lagou.edu.repository.UserRepositry;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * Created by shixi  on 2021/1/28
 */
@Service
public class UserServiceImpl {

    @Autowired
    private UserRepositry userRepositry;

    @Autowired
    private CodeService codeService;


    public boolean register(String email, String password, String code) {
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(password)){
            return false;
        }
        if(!isRegistered(email)){//未注册的
            //校验验证码
            if(codeService.validate(email,code) == 0 ) {
                User user = new User();
                user.setEmail(email);
                user.setPassword(password);
                user.setToken(buildToken(email, password));
                userRepositry.saveAndFlush(user);
                return true;
            }
        }
        return false;
    }

    //生成token
    private String buildToken(String email, String password) {
        String str = email+password;
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }


    public boolean isRegistered(String email) {
        if(StringUtils.isEmpty(email)){
            return false;
        }
        return userRepositry.findByEmail(email)!=null;
    }


    public User login(String email, String password) {
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password)){
            return null;
        }
        return userRepositry.findByEmailAndPassword(email, password);
    }


    public String getEmailByToken(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }
        User user = userRepositry.findByToken(token);
        if(user!=null){
            return user.getEmail();
        }
        return null;
    }
}